package routerServer

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/AjaxResult"
	"github.com/gin-gonic/gin"
	"go-fox-edge-kernel-gateway/controller"
	"net/http"
)

type authHandler struct {
}

func (e *authHandler) registerRouter() {
	e.register("auth")
}

func (e *authHandler) register(relativePath string) {
	if relativePath == "" {
		return
	}

	engine.GET(relativePath+"/*res", func(context *gin.Context) {
		e.handleRequest(context, "GET")
	})
	engine.DELETE(relativePath+"/*res", func(context *gin.Context) {
		e.handleRequest(context, "DELETE")
	})
	engine.PUT(relativePath+"/*res", func(context *gin.Context) {
		e.handleRequest(context, "PUT")
	})
	engine.POST(relativePath+"/*res", func(context *gin.Context) {
		e.handleRequest(context, "POST")
	})
}

func (e *authHandler) handleRequest(context *gin.Context, method string) {
	res := context.Param("res")

	if res == "/login" && "GET" == method {
		data, err := controller.Auth.Login(context)
		e.respond(context, data, err)
	}
	if res == "/tokenInfo" && "GET" == method {
		data, err := controller.Auth.TokenInfo(context)
		e.respond(context, data, err)
	}
	if res == "/userinfo" && "GET" == method {
		data, err := controller.Auth.GetUserInfo(context)
		e.respond(context, data, err)
	}
	if res == "/usermenu" && "GET" == method {
		data, err := controller.Auth.GetUserMenu(context)
		e.respond(context, data, err)
	}
	if res == "/logout" && "DELETE" == method {
		data, err := controller.Auth.Logout(context)
		e.respond(context, data, err)
	}
}

func (e *authHandler) respond(context *gin.Context, data map[string]any, err error) {
	if err != nil {
		context.JSON(http.StatusOK, AjaxResult.Error(err.Error(), nil))
	} else {
		context.JSON(http.StatusOK, AjaxResult.Success("操作成功", data))
	}
}
